package org.jadelyre.core;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.nio.ByteBuffer;
import java.nio.channels.AsynchronousSocketChannel;
import java.nio.channels.CompletionHandler;
import java.util.concurrent.Semaphore;

public class WriteCompletionHandler implements CompletionHandler<Integer, Channel> {
    private static final Logger logger = LoggerFactory.getLogger(WriteCompletionHandler.class);

    private AsynchronousSocketChannel asynchronousSocketChannel;
    private ByteBuffer writeByteBuffer;
    private Semaphore semaphore = new Semaphore(1);
    public WriteCompletionHandler(AsynchronousSocketChannel asynchronousSocketChannel) {
        this.asynchronousSocketChannel = asynchronousSocketChannel;
    }

    @Override
    public void completed(Integer result, Channel channel) {
        if (writeByteBuffer.hasRemaining()) {
            asynchronousSocketChannel.write(writeByteBuffer, channel, this);
        } else {
            semaphore.release();
        }
    }

    @Override
    public void failed(Throwable exc, Channel channel) {
        if (logger.isErrorEnabled()) {
            logger.error("写数据失败：{}", exc.toString());
        }
        semaphore.release();
    }

    public WriteCompletionHandler setWriteByteBuffer(ByteBuffer writeByteBuffer) {
        this.writeByteBuffer = writeByteBuffer;
        return this;
    }

    public AsynchronousSocketChannel getAsynchronousSocketChannel() {
        return asynchronousSocketChannel;
    }

    public Semaphore getSemaphore() {
        return semaphore;
    }
}
